﻿/// <reference path="jquery.min.js" />
/// <reference path="jquery.form.js" />

(function ($) {
    $.fn.extend({
        tianv_value: function (data) {
            if (!data) return;

            var data = data;
            return this.each(function () {
                var form = $(this);
                $.each(data, function (name, value) {
                    var input = form.find('[name=' + name + ']');
                    if (input.length <= 0) return;
                    var tagType = input.attr('type');
                    if (tagType == 'checkbox' || tagType == 'radio') {
                        input.each(function () {
                            var me = $(this);
                            if ((',' + value + ',').indexOf(',' + me.val() + ',') >= 0) {
                                me.attr('checked', 'checked');
                            }
                            else {
                                me.removeAttr('checked');
                            }
                        });
                    }
                    else {
                        input.val(value);
                    }
                });
            });
        }
    })
})(jQuery);

(function ($) {
    $.fn.extend({
        tianv_validate: function (options) {

            var defaults = {
                validate: null,
                ajaxBegin: function(form){
                    var loading = form.data('loading');
                    if (!loading){
                        loading = $('<div class="formLoading">处理中...</div>');
                        loading.height(form.height());
                        form.data('loading', loading);
                    }
                    form.hide();
                    form.parent().append(loading);
                    loading.show();
                },
                ajaxComplete: function(form){
                    var loading = form.data('loading');
                    if (loading){
                        loading.hide();
                    }
                    form.show();
                },
                ajaxResult: function(opts, form, data ){
                    if (data.success) {
                        if( data.str == 'url' ){
                            window.location = data.args;
                        }
                        else{
                            form.find('span.result').html( data.args );
                            form.clearForm();
                        }
                    }
                    else {
                        if( data.str ){
                            var input = form.find('[name=' + data.str + ']');
                            if( input.length >=1 ){
                                opts.showError(form, input, data.str, data.args);
                            }
                            else{
                                form.find('span.result').addClass('error').html( data.args );
                            }
                        }
                        else{
                            form.find('span.result').addClass('error').html( data.args );
                        }
                    }
                },
                updateValidateCode: function(form){
                    var vcode_input = form.find('input[name=vcode]');
                    if( vcode_input.length>=1 ) {
                        vcode_input.val('');
                    }
                    else{
                        return;
                    }
                    var vcode_img = form.parent().find('img');
                    if( vcode_img.length>=1 ){
                        var vcode_img_src = vcode_img.attr('src');
                        if( vcode_img_src.indexOf( '?')>=0 ){
                            vcode_img_src = vcode_img_src.substring( 0, vcode_img_src.indexOf( '?'));
                        }
                        var t = 150000 - Math.floor(Math.random() * 100000);
                        vcode_img.attr('src', vcode_img_src + '?_=' + t);
                    }
                },
                showError: function(form, input, name, str) {
                    var span = (input && input.parent().find('span').length >= 1) ? input.parent().find('span') : form.find('span.result');
                    span.html(str).addClass('error');
                },
                hideError: function(form, input, name) {
                    var span = (input && input.parent().find('span').length >= 1) ? input.parent().find('span') : form.find('span.result');
                    span.html('&nbsp').removeClass('error');
                }
            };

            var opts = $.extend(defaults, options);

            return this.each(function () {
                var form = $(this);
                bindForm(form, opts);
            });
        }
    });

    function checkInput(opts, form, input, name, rule, msg, focus, notCheckRemote) {
        opts.hideError(form, input, name);
        var tagType = input.attr('type');
        if (tagType == 'checkbox' || tagType == 'radio') {
            if (rule.required && input.filter(":checked").length <= 0) {
                if (focus) input.first().focus();
                opts.showError(form, input, name, msg.required);
                return;
            }
            if (rule.minlength && input.filter(":checked").length < rule.minlength) {
                if (focus) input.first().focus();
                opts.showError(form, input, name, msg.minlength);
                return;
            }
            if (rule.maxlength && input.filter(":checked").length > rule.maxlength) {
                if (focus) input.first().focus();
                opts.showError(form, input, name, msg.maxlength);
                return;
            }
            return true;
        }
        else {
            var val = input.val();

            if (rule.required && val.length <= 0) {
                if (focus) input.focus();
                opts.showError(form, input, name, msg.required);
                return;
            }
            if (rule.minlength && val.length < rule.minlength) {
                if (focus) input.focus();
                opts.showError(form, input, name, msg.minlength);
                return;
            }
            if (rule.maxlength && val.length > rule.maxlength) {
                if (focus) input.focus();
                opts.showError(form, input, name, msg.maxlength);
                return;
            }
            if (rule.equalto) {
                var ev = form.find('[name=' + rule.equalto + ']').val();
                if (val != ev) {
                    if (focus) input.focus();
                    opts.showError(form, input, name, msg.equalto);
                    return;
                }
            }
            if (rule.epression) {
                if (focus) input.focus();

                var rx = new RegExp(rule.epression);
                if (!rx.test(val)) {
                    opts.showError(form, input, name, msg.epression);
                    return;
                }
            }

            if (!notCheckRemote && rule.remote) {
                var oaj = input.data('ajax');
                if (oaj) oaj.abort();

                var aj = $.ajax({
                    dataType: 'json',
                    type: 'POST',
                    url: rule.remote + (rule.remote.indexOf('?') >= 0 ? '&' : '?') + 'method=validate',
                    data: { name: name, val: val },
                    success: function (data) {
                        if (data.success) {
                        }
                        else {
                            if (focus) input.focus();
                            opts.showError(form, input, name, data.str);
                        }
                    }
                });
                input.data('ajax', aj);
                return;
            }

            return true;
        }
    }

    function bindInput(opts, form, name, rule, msg) {
        var input = form.find('[name=' + name + ']');
        if (input.length <= 0) return;
        input.keyup(function (event) {
            if( event.keyCode == 9 )            return true;
            checkInput(opts, form, input, name, rule, msg, true);
        });
        input.mouseup(function () {
            checkInput(opts, form, input, name, rule, msg, true);
        });
        input.change(function () {
            checkInput(opts, form, input, name, rule, msg, false);
        });
    }

    function bindForm(form, opts) {
        //绑定输入框
        var validate = opts.validate;
        $.each(validate.rules, function (name, rule) {
            var msg = validate.messages[name];
            bindInput(opts, form, name, rule, msg);
        });
        //更新验证码
        opts.updateValidateCode(form);
        form.find('input[name=vcode]').parent().click( function(){
            opts.updateValidateCode(form);
        });
        //绑定表单
        form.submit(function () {
            //验证输入
            var focus = true;
            $.each(validate.rules, function (name, rule) {
                var msg = validate.messages[name];
                var input = form.find('[name=' + name + ']');
                if (input.length <= 0) return;
                var ci = checkInput(opts, form, input, name, rule, msg, focus, true);
                if (!ci) focus = false;
            });
            if (!focus) {
                return false;
            }
            //数据提交
            opts.ajaxBegin(form);
            form.ajaxSubmit({
                dataType: 'json',
                success: function (data) {
                    opts.ajaxComplete(form);
                    opts.ajaxResult( opts, form, data );
                    opts.updateValidateCode(form);
                },
                error: function (a, b, c) {
                    opts.ajaxComplete(form);
                    alert([a, b, c]);
                }
            });
            return false;
        });
    }

})(jQuery);